package com.lmy.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmy.common.constant.ProductConstant;
import com.lmy.common.to.SkuReductionTo;
import com.lmy.common.to.SpuBoundTo;
import com.lmy.common.to.es.SkuEsModel;
import com.lmy.common.utils.PageUtils;
import com.lmy.common.utils.Query;
import com.lmy.common.utils.R;
import com.lmy.product.entity.*;
import com.lmy.product.feign.CouponFeignService;
import com.lmy.product.feign.SearchFeignService;
import com.lmy.product.feign.WareFeignService;
import com.lmy.product.mapper.SpuInfoDao;
import com.lmy.product.service.*;
import com.lmy.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDao spuInfoDao;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        return getPageUtils(params, new QueryWrapper<SpuInfoEntity>());
    }

    @Transactional
    @Override
    public void SpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuInfo(spuInfoEntity);
        // 2、保存Spu的描述图片pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //将图片数组用逗号分隔成字符串形式保存
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        // 3、保存spu的图片集pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);
        // 4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(bas -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(bas.getAttrId());
            AttrEntity attrEntity = attrService.getById(bas.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(bas.getAttrValues());
            productAttrValueEntity.setQuickShow(bas.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);
        // 5、保存spu的积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        //调用远程服务
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        // 5、保存当前spu对应的所有sku信息；
        List<Skus> skus = vo.getSkus();
        if (skus != null && !skus.isEmpty()) {
            skus.forEach(item -> {
                String dafaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        dafaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(dafaultImg);
                // 5.1）、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);
                // 5.2）、sku的图片信息；pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，返回false就是不需要
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                // 5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> valueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(valueEntities);
                // 5.4）、sku的优惠、满减等信息；guLimaLL_sms->sms_sku_Ladder\sms_sku_fuLL
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0
                        || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    R rt = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (rt.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }


    }

    /**
     * 保存spu基本信息pms_spu_info
     *
     * @param spuInfoEntity
     */
    @Override
    public void saveSpuInfo(SpuInfoEntity spuInfoEntity) {
        spuInfoDao.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        if (params.size() == 3) {
            return getPageUtils(params, spuInfoEntityQueryWrapper);
        } else {
            String key = params.get("key").toString();
            if (!StringUtils.isEmpty(key)) {
                spuInfoEntityQueryWrapper.and(wq -> {
                    wq.eq("id", key).or().like("spu_name", key);
                });
            }
            String status = params.get("status").toString();
            if (!StringUtils.isEmpty(status)) {
                spuInfoEntityQueryWrapper.eq("publish_status", status);
            }
            String brandId = params.get("brandId").toString();
            if (!StringUtils.isEmpty(brandId)) {
                spuInfoEntityQueryWrapper.eq("brand_id", brandId);
            }
            String catelogId = params.get("catelogId").toString();
            if (!StringUtils.isEmpty(catelogId)) {
                spuInfoEntityQueryWrapper.eq("catalog_id", catelogId);
            }
            return getPageUtils(params, spuInfoEntityQueryWrapper);
        }
    }

    @Override
    public void up(Long spuId) {
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<>();
        //查出spuId对应的sku信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.selectSkuBySpuId(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //todo 4 查出当前sku的所有可以用来被检索的规格属性
        //通过spuId查询所有的数据集合
        List<ProductAttrValueEntity> entities = productAttrValueService.baseAttrListforspu(spuId);
        //将数据集合中的id提出来
        List<Long> attrIds = entities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //查出符合条件的id集合
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        //从集合entities过滤出符合条件的集合
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.attrs> attrsList = entities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.attrs attrs = new SkuEsModel.attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());
        //todo 1发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> map = null;
        try {
            R<List<SkuStockVo>> skuStock = wareFeignService.getSkuStock(skuIds);
            map = skuStock.getData().stream()
                    .collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::isHasStock));
        } catch (Exception e) {
            log.error("库存系统查询异常" + e);
        }


        //封装每个sku信息
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> esModels = skuInfoEntities.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            if (finalMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalMap.get(sku.getSkuId()));
            }

            //todo 2热度评分 0(默认)
            skuEsModel.setHotScore(0L);
            //todo 3查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());
        //todo 将数据发给es存储
        R r = searchFeignService.saveProduct(esModels);
       if (r.getCode()==0){
           //远程调用成功
           // todo 6修改当前spu的状态为上架
           baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
       }else {
           //TODO 调用失败重复调用机制
       }
    }

    @NotNull
    private PageUtils getPageUtils(Map<String,Object> params, QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params)
                , spuInfoEntityQueryWrapper);
        return new PageUtils(page);
    }


}